<?php

namespace App\Http\Controllers\v1;

use App\Http\Resources\CourseCollection;
use App\Models\Course;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CourseController extends Controller
{
    /**
     * 课程列表
     * 可选参数limit,offset,category_id,kw
     * 按照创建时间倒序排列
     * @param Request $request
     * @return CourseCollection
     */
    public function index(Request $request)
    {
//        limit
        $limit = $request->get('limit', 5);
        $limit = min(max($limit, 1), 20);
//        offset
        $offset = $request->get('offset', 0);

        $data = new Course();
//        分类ID
        $category_id = $request->get('category_id');
        $category_id && $data = $data->where('category_id', $category_id);

//        kw
        $kw = $request->get('kw');

        $data = $data->limit($limit)
            ->with(['category','classes'])
            ->where('name', 'LIKE', '%' . $kw . '%')
            ->offset($offset)
            ->orderBy('created_at', 'desc')
            ->get();
        return new CourseCollection($data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * 获取一个课程的信息 (分类，课时)
     * @param $id
     * @return \App\Http\Resources\Course
     */
    public function show($id)
    {
        $data = Course::with(['category','classes'])->find($id);
        return new \App\Http\Resources\Course($data);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
